<template>
  <div class="ai_wrap" ref="scrollWrap">
    <div class="content">
      <div class="top_wrap">
        <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5077">
          <path
              d="M802.133333 170.666667v682.666666h-597.333333V170.666667h597.333333m0-85.333334h-597.333333a85.333333 85.333333 0 0 0-85.333333 85.333334v682.666666a85.333333 85.333333 0 0 0 85.333333 85.333334h597.333333a85.333333 85.333333 0 0 0 85.333334-85.333334V170.666667a85.333333 85.333333 0 0 0-85.333334-85.333334z"
              fill="#ffffff" p-id="5078"></path>
          <path
              d="M674.133333 298.666667h-341.333333a42.666667 42.666667 0 0 0 0 85.333333h341.333333a42.666667 42.666667 0 0 0 0-85.333333zM503.466667 469.333333h-170.666667a42.666667 42.666667 0 0 0 0 85.333334h170.666667a42.666667 42.666667 0 0 0 0-85.333334zM631.466667 640h-298.666667a42.666667 42.666667 0 0 0 0 85.333333h298.666667a42.666667 42.666667 0 0 0 0-85.333333z"
              fill="#ffffff" p-id="5079"></path>
        </svg>
        <h6 class="business_title">{{ title }}</h6>
      </div>
      <div class="form_wrap">
        <van-field
            v-model="userName"
            name="姓名"
            label="姓名"
            disabled
            placeholder="上传身份证自动识别"
        />
        <van-field
            v-model="userId"
            type="number"
            name="身份证号"
            label="身份证号"
            disabled
            placeholder="上传身份证自动识别"
        />
        <van-field
            v-model="phoneNumber"
            label="手机号"
            placeholder="请输入手机号"
        >
          <template #button>
            <van-button size="small" round :color="downNum>=0?'#cccccc':'#5482eb'" @click="sendPhone()" type="primary">
              {{ sendBtnText }}
            </van-button>
          </template>
        </van-field>
        <van-field
            v-model="verificationCode"
            center
            clearable
            label="短信验证码"
            placeholder="请输入短信验证码"
        >
        </van-field>
        <p class="form_dt">身份证</p>
        <div class="upload_row">
          <van-uploader v-model="newMaterialA"
                        name="身份证正面"
                        :before-read="beforeRead"
                        :after-read="startUpload"
                        :deletable="true"
                        @oversize="onOversize"
                        :preview-options="previewObj"
                        @delete="file=>deleteImg(file,item.materialName)"
                        :max-size="10*1024*1024"
                        class="idcard_a" preview-size="120"
                        :multiple=false max-count="1"/>
          <van-uploader v-model="newMaterialB"
                        name="身份证反面"
                        :before-read="beforeRead"
                        :after-read="startUpload"
                        :deletable="true"
                        @oversize="onOversize"
                        :preview-options="previewObj"
                        @delete="file=>deleteImg(file,item.materialName)"
                        :max-size="10*1024*1024"
                        class="idcard_b" preview-size="120"
                        :multiple=false max-count="1"/>
        </div>
        <p class="form_dt">户口簿<span class="nt2">（户口簿本人页）</span></p>
        <div class="upload_row">
          <van-uploader v-model="newMaterialC"
                        name="户口簿"
                        :before-read="beforeRead"
                        :after-read="startUpload"
                        :deletable="true"
                        @oversize="onOversize"
                        :preview-options="previewObj"
                        @delete="file=>deleteImg(file,item.materialName)"
                        :max-size="10*1024*1024"
                        class="hkb" preview-size="120"
                        :multiple=false max-count="1"/>
        </div>
      </div>
      <div style="margin:30px 16px;">
        <van-button round block type="primary" @click="submit">
          提交
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import axios from "axios";

export default {
  name: 'HomeView',
  data() {
    return {
      title: "城乡居民基本养老保险参保登记网上预审",
      userName: "",
      userId: "",
      uploadCount: 3,
      newMaterialA: [],
      newMaterialB: [],
      newMaterialC: [],
      newUploadObj: [],
      sendBtnText: "发送验证码",
      verificationCode:"",
      downNum: -1,
      phoneNumber: "",
      previewObj: {
        showIndex: false
      }
    }
  },
  created() {
    //this.fetchData('你好啊')
    this.$nextTick(() => {
      this.scrollObj = new BScroll(this.$refs.scrollWrap, {
        click: true,
      })
    })
  },
  setup() {

  },
  methods: {
    verifyNumber(phone) {
      if ((/^1[345789]\d{9}$/.test(phone))) {
        return true
      } else {
        return false
      }
    },
    sendPhone() {
      if (this.downNum > 0) return
      //发送验证码
      let verifyResult = this.verifyNumber(this.phoneNumber)
      if (!verifyResult) {
        this.$dialog.alert({
          message: '请正确填写您的手机号码！',
          confirmButtonColor: '#5482eb',
        }).then(() => {
          console.log("phone number is error")
        })
        return
      }
      const url = `https://www.pengzhou.org.cn/api/znsp/sendSmsVerificationCode?tell=${this.phoneNumber}`;
      try {
        fetch(url, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
        }).then(async response =>  {
          if (response.status==200 && response.ok) {
            this.$toast('验证码已发送成功');
            this.downNum = 60
            this.timerFn()
          } else {
            this.$toast(response.data.msg);
          }
        })
      } catch (error) {
        this.$toast('获取验证码失败');
        console.error('请求失败:', error);
      }
    },
    timerFn(){
      let timer=setInterval(()=>{
        if(this.downNum<0){
          this.sendBtnText="发送验证码";
          clearInterval(timer)
        }else {
          this.sendBtnText=this.downNum>0?(this.downNum)+"s后重新获取":'发送验证码';
          this.downNum--;
        }
      },1000);
    },
    deleteImg(file, name) {
      console.log("delete file", file, name)
      this.newUploadObj = this.newUploadObj.filter(item => item.name !== name);
    },
    beforeRead(file) {
      if (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/heic' || file.type == '') {
        return true
      }
      this.$toast.fail("请上传图片格式的身份证材料！")
      return false
    },
    onOversize() {
      this.$toast.fail("图片大小不能超过10M！")
    },
    submit(){
      if(this.phoneNumber==""){
        this.$toast('手机号码不能为空');
        return
      }else if(this.verificationCode==""){
        this.$toast('验证码不能为空');
        return
      }else if(this.newUploadObj.length<this.uploadCount){
        this.$toast('资料上传不全，请核查');
        return
      }else{
        //提交数据
        //console.log(decodeURIComponent(JSON.stringify(this.newUploadObj)))
        const url = "https://www.pengzhou.org.cn/api/znsp/intoZNSPValue";
        axios.post(url,{
            idcard:this.userId,
            name:this.userName,
            tell:this.phoneNumber,
            code:this.verificationCode,
            oid:'2c98b0197a2fdce7017a376fa8b50f30',
            json:JSON.stringify(this.newUploadObj)
        },{
          headers: {
            'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
          }
        }).then(response => {
          console.log("%%%%%%%%%%%%%",response)
          if (response.data && response.data.success) {
            //提交成功
            window.location.href = response.data.url;
          }else{
            this.$toast(response.data.msg);
          }}).catch(error => {
          console.error('Error:', error);
        });
      }
    },
    startUpload(file, flag) {
      file.status = 'uploading';
      let formData = new FormData();
      if (file instanceof Array && file.length) {
        for (let i = 0; i < file.length; i++) {
          const element = file[i].file;
          formData.append("file[]", element);
        }
      } else {
        console.log(file.file)
        formData.append("file", file.file);
      }
      //上传接口
      let typename = "";
      if(flag.name.indexOf("身份证")>-1){
        typename = "idcard"
      }
      //else if(flag.name.indexOf("户口簿")>-1){
      //  typename = "residencebook"
      //}
      const url = "https://www.pengzhou.org.cn/api/znsp/ocrResult?type="+typename+"&fileName="+flag.name;
      try {
        axios.post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data' // 不需要设置Content-Type，axios会自动设置，但如果需要自定义，可以添加此行。默认情况下不需要设置。
          }
        }).then(response => {
          console.log("%%%%%%%%%%%%%",response)
          if (response.data && response.data.success) {
            //上传成功未入库
            file.status = 'done';
            file.file = null
            file.content = ""
            file.url = 'https://www.pengzhou.org.cn/'+response.data.url
            console.log(file.url)
            if(typename == "idcard"){
              if(response.data.name !== undefined)
              this.userName = response.data.name
              if(response.data.idcard !== undefined)
                this.userId = response.data.idcard
            }
            let valueList = {
              url: response.data.url,
              name: flag.name
            }
            this.newUploadObj.push(valueList)
          }else{
            file.status = 'done';
            file.file = null
            file.content = ""
            file.url = ""
            this.$toast('文件格式有误！');
          }}).catch(error => {
                  console.error('Error:', error);
        });
        // fetch(url, {
        //   method: 'POST',
        //   headers: {
        //     'Content-Type': 'multipart/form-data',
        //   },
        //   body: formData
        // }).then(async response =>  {
        //   console.log("%%%%%%%%%%%%%",response)
        //   if (response.data && response.data.success) {
        //     //上传成功未入库
        //     file.status = 'done';
        //     file.file = null
        //     file.content = ""
        //     file.url = response.data.url.replace("/api", "/gxsys")
        //     let valueList = {
        //       url: response.data.url,
        //       name: flag.name
        //     }
        //     this.newUploadObj.push(valueList)
        //   }
        // })
      } catch (error) {
        this.$toast('获取验证码失败');
        console.error('请求失败:', error);
      }
    },
  }
}
</script>

<style scoped>
.ai_wrap {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-size: contain;
  text-align: left;
}

.top_wrap {
  width: 100%;
  background: #5482eb;
  display: flex;
  padding: 16px;
  align-items: center;
}

.icon {
  width: 2em;
  height: 2em;
  margin-right: 5px;
}

.business_title {
  font-size: 1rem;
  font-weight: normal;
  color: #fff;
}

/deep/ .van-field--disabled .van-field__label {
  color: #4d4d4d;
  font-size: 0.9rem;
}

.form_dt {
  color: #4d4d4d;
  font-size: 0.9rem;
  margin-left: 1rem;
  height: 3rem;
  line-height: 3rem;
}

.idcard_a, .hkb {
  margin-left: 1rem;
}

.upload_row {
  overflow: hidden;
}

.nt2 {
  color: #adabab;
  margin-left: 0.5rem;
  font-size: 0.8rem;
}
.content{
  padding-bottom: 20px;
}
/deep/ .material_item .van-cell__value {
  flex: none;
  width: 0;
}

/deep/ .van-image__img {
  object-fit: contain !important;
}

/deep/ .idcard_a .van-uploader__upload {
  background: url("../assets/idcard0.png") #f7f8fa center center no-repeat;
  background-size: contain;
}

/deep/ .idcard_b .van-uploader__upload {
  background: url("../assets/idcard1.png") #f7f8fa center center no-repeat;
  background-size: contain;
}

/deep/ .van-uploader {
  float: left;
}
</style>
